<template>
    <div class="testing-index yuan-container">
        <a-card title="销售管理">
            <div class="filter-panel">
                <div class="filter-list" style="float: right;" v-if="$utilCheckPermission(['sellManagementAdd'])">
                    <a-button type="primary" @click="add">新增</a-button>
                    <a-button type="primary" @click="downloadTemplate" v-if="$utilCheckPermission(['sellManagementDownload'])">下载模板</a-button>
                    <a-button type="primary" @click="showImportModal" v-if="$utilCheckPermission(['sellManagementImport'])">导入</a-button>
                </div>
            </div>
            <div class="table">
                <a-table bordered :rowKey="getRowKey" :data-source="pageList" :columns="columns" :pagination="pagination"
                    :loading="loading">
                </a-table>
            </div>
        </a-card>
        <a-modal width="80%" :visible="visible" :title="modalOption.title" @ok="modalOption.onOk" @cancel="modalOption.onCancel"
            :okText="modalOption.okText" :cancelText="modalOption.cancelText" class="yuan-modal testing-add-modal">
            <a-spin tip="Loading..." :spinning="formLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :label-col="{ style: { width: '100px' } }" :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">
                        <div style="margin-bottom: 20px" class="form-panel-box yuan-form-col3">
                            <a-row>
                                <a-col :span="24">
                                    <a-form-model-item style="width: 100%" label="客户名称" prop="clientName">
                                        <a-select :disabled="checked"  style="width: 100%" v-model="formData.clientName"
                                                  placeholder="请选择客户名称" :filter-option="$filterOption" show-search>
                                            <a-select-option v-for="(item) in clientList" :key="item.id"
                                                             :value="item.name">{{item.name}}</a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="8">
                                    <a-form-model-item class="yuan-form-item" label="物料类型" :prop="'productType'">
                                        <a-select :disabled="checked" class="yuan-form-input" v-model="formData.productType"
                                                  placeholder="请选择物料类型" @change="getVarietyList">
                                            <a-select-option value="中药饮片">中药饮片</a-select-option>
                                            <a-select-option value="直服饮片">直服饮片</a-select-option>
                                            <a-select-option value="单方饮片">单方饮片</a-select-option>
                                        </a-select>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item class="yuan-form-item" label="ERP单号" prop="erpOdd">
                                        <a-input :disabled="checked" class="yuan-form-input" v-model="formData.erpOdd"
                                                 placeholder="erp单号"></a-input>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item class="yuan-form-item" label="销售时间" prop="sellTime">
                                        <a-date-picker :disabled="checked" :locale="locale" class="yuan-form-input"
                                                       valueFormat="YYYY-MM-DD" v-model="formData.sellTime" placeholder="请选择销售时间" />
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="8">
                                    <a-form-model-item class="yuan-form-item" label="品种数量" prop="principal">
                                        <span>{{varietyNum}}</span>
                                    </a-form-model-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-model-item class="yuan-form-item" label="销售总数量" prop="principal">
                                        <span>{{sellTotalNum}}kg</span>
                                    </a-form-model-item>
                                </a-col>
                            </a-row>
                        </div>
                        <div v-for="(item,i) in categoryList" :key="i" style="margin-bottom: 20px">
                            <div style="margin-bottom: 20px" class="form-panel-box yuan-form-col3">
                                <a-row>
                                    <a-col :span="8">
                                        <a-form-model-item class="yuan-form-item" label="选择批号">
                                            <a-select v-if="formData.productType" :disabled="checked" v-model="item.batch"
                                                placeholder="选择批号" @change="getDetailInfo($event,i)"
                                                :filter-option="$filterOption" show-search>
                                                <a-select-option v-for="child in batchList" :key="child"
                                                    :value="child">{{child}}</a-select-option>
                                            </a-select>
                                            <span v-else>请先选择物料类型</span>
                                        </a-form-model-item>
                                    </a-col>
                                    <a-col :span="8">
                                        <a-form-model-item class="yuan-form-item" label="选择品种">
                                            <a-select :disabled="checked" v-if="formData.productType" class="yuan-form-input"
                                                v-model="item.materialCode" placeholder="请选择选择品种"
                                                @change="getDetailByVariety($event,i)" :filter-option="$filterOption" show-search>
                                                <a-select-option v-for="child in varietyList" :key="child.materialCode"
                                                    :value="child.materialCode">{{child.varietyName}}</a-select-option>
                                            </a-select>
                                            <span v-else>请先选择物料类型</span>
                                        </a-form-model-item>
                                    </a-col>
                                    <a-col :span="8">
                                        <a-form-model-item class="yuan-form-item" label="中药等级">
                                            <span v-if="item.materialCode">{{item.medicineClass}}</span>
                                            <span v-else>请先选择批号</span>
                                        </a-form-model-item>
                                    </a-col>
                                </a-row>
                                <a-divider />
                                <a-row>
                                    <a-col :span="5">
                                        <a-form-model-item class="yuan-form-item" label="产品大类">
                                            <span>{{item.productBigKind}}</span>
                                        </a-form-model-item>
                                    </a-col>
                                    <a-col :span="4">
                                        <a-form-model-item class="yuan-form-item" label="包装规格">
                                            <span>{{item.discretion}}</span>
                                        </a-form-model-item>
                                    </a-col>
                                    <a-col :span="6">
                                        <a-form-model-item class="yuan-form-item" label="销售重量" prop="sellNum">
                                            <a-input :disabled="checked" class="yuan-form-input" v-model="item.sellNum"
                                                placeholder="销售重量" suffix="kg"></a-input>
                                        </a-form-model-item>
                                    </a-col>
                                </a-row>
                            </div>
                            <div style="text-align: right">
                                <a-button :disabled="checked" v-if="i===categoryList.length-1" style="margin-right: 10px"
                                    type="primary" @click="addCategory">添加</a-button>
                                <a-button :disabled="checked" v-if="i!=0" type="danger" @click="deleteCategory(i)">删除</a-button>
                            </div>
                        </div>
                    </div>
                </a-form-model>
            </a-spin>
        </a-modal>

        <a-modal width="80%" :visible="checkModalOption.visible" title="查看" @ok="checkModalOption.onOk()" @cancel="checkModalOption.onOk()"
                 :okText="checkModalOption.okText" :cancelText="checkModalOption.cancelText" class="yuan-modal testing-add-modal">
            <a-card>
                <a-table bordered :rowKey="getRowKey" :data-source="checkTableData" :columns="checkTableColumns" :pagination="false">
                </a-table>
            </a-card>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import { h } from "vue";
import nextApi from "@/api/nextApi";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
import { downLoadFile } from "@/utils/index";

@Component({
    components: {},
})
export default class extends Vue {
    locale = locale;
    previewVisible = false;
    loading = false;
    pagination = {
        pageSize: 10,
        current: 1,
        total: 0,
        showTotal: (total: number) => `共${total}条`,
        onChange: this.pageChange,
    };
    pageList: any = [];
    columns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center",
            customRender: (text: string, record: any, index: number) => `${index + 1}`,
        },
        {
            align: "center",
            dataIndex: "erpOdd",
            key: "erpOdd",
            title: "ERP单号",
        },
        {
            align: "center",
            dataIndex: "clientName",
            key: "clientName",
            title: "客户名称",
        },
        {
            align: "center",
            dataIndex: "varietyNum",
            key: "varietyNum",
            title: "品种数量",
        },
        {
            align: "center",
            dataIndex: "sellSum",
            key: "sellSum",
            title: "销售总数量",
        },
        {
            align: "center",
            dataIndex: "sellTime",
            key: "sellTime",
            title: "销售时间",
        },
        {
            align: "center",
            dataIndex: "action",
            key: "action",
            title: "操作",
            width: 260,
            customRender: (text: string, record: any, index: number) => {
                const statusDom = h(
                    "a-popconfirm",
                    {
                        style: { marginRight: "5px" },
                        props: {
                            title: "确定要删除吗？",
                            okText: "确定",
                            cancelText: "取消",
                        },
                        on: { confirm: () => this.remove(record) },
                    },
                    [
                        h(
                            "a-button",
                            {
                                props: {
                                    icon: "tool",
                                    type: "danger",
                                    size: "small",
                                },
                            },
                            "删除"
                        ),
                    ]
                );
                const editBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "edit", type: "primary", size: "small" },
                        on: { click: () => this.editDetail(record) },
                    },
                    "编辑"
                );
                const detailBtn = h(
                    "a-button",
                    {
                        style: { marginRight: "5px" },
                        props: { icon: "edit", type: "primary", size: "small" },
                        on: { click: () => this.check(record) },
                    },
                    "查看"
                );
                const btn: any[] = [];
                if (this.$utilCheckPermission(["sellManagementCompile"])) btn.push(editBtn);
                if (this.$utilCheckPermission(["sellManagementRemove"])) btn.push(statusDom);
                if (this.$utilCheckPermission(["sellManagementDetails"])) btn.push(detailBtn);
                return h("div", btn);
            },
        },
    ];
    checkTableColumns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            align: "center",
            customRender: (text: string, record: any, index: number) => `${index + 1}`,
        },
        {
            title:"客户名称",
            dataIndex: "clientName",
            key: "clientName",
            align: "center",
        },
        {
            title:"ERP单号",
            dataIndex: "erpOdd",
            key: "erpOdd",
            align: "center",
        },
        {
            align: "center",
            dataIndex: "varietyName",
            key: "varietyName",
            title: "品种名称",
        },
        {
            align: "center",
            dataIndex: "batch",
            key: "batch",
            title: "批号",
        },
        {
            align: "center",
            dataIndex: "materialCode",
            key: "materialCode",
            title: "物料编码",
        },
        {
            align: "center",
            dataIndex: "productBigKind",
            key: "productBigKind",
            title: "产品大类",
        },
        {
            align: "center",
            dataIndex: "productType",
            key: "productType",
            title: "物料类型",
        },
        {
            align: "center",
            dataIndex: "discretion",
            key: "discretion",
            title: "装量",
        },
        {
            align: "center",
            dataIndex: "sellNum",
            key: "sellNum",
            title: "销售数量",
        },
    ]
    formLoading = false;
    modalOption = {
        title: "新增",
        okText: "保存",
        cancelText: "取消",
        onOk: () => {
            this.modalOk();
        },
        onCancel: () => {
            this.closeModal();
        },
    };
    checkModalOption = {
        visible:false,
        title: "查看",
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
            this.checkModalOption.visible = false;
        },
    }
    // 导入相关
    importModalVisible = false;
    importLoading = false;
    selectedFile: File | null = null;
    categoryList: any = [
        {
            varietyName: "",
            materialCode: "",
            batch: "",
            productBigKind: "",
            discretion: "",
            sellNum: "",
        },
    ];
    // 表单数据
    formData: any = {
        clientName: "",
        sellTime: "",
        varietyNum: "",
        sellSum: "",
        sellDetails: [],
    };
    rules = {
        clientName: [{ required: true, message: "请选择客户名称" }],
        sellTime: [{ required: true, message: "请选择销售时间" }],
        productType: [{ required: true, message: "请选择物料类型" }],
    };
    varietyNum = "";
    @Watch("categoryList")
    onCategoryListChange(val) {
        if (val) {
            this.varietyNum = val.length;
        }
    }
    get sellTotalNum() {
        if (this.categoryList) {
            let num = 0;
            this.categoryList.forEach((item) => {
                num += Number(item.sellNum);
            });
            return num.toFixed(2);
        }
    }
    addCategory() {
        this.categoryList.push({
            varietyName: "",
            materialCode: "",
            batch: "",
            productBigKind: "",
            discretion: "",
            sellNum: "",
        });
    }
    deleteCategory(i) {
        this.categoryList.splice(i, 1);
    }
    getRowKey(item: any) {
        return item.id;
    }
    //查询客户
    clientList: any = [];
    async getClientList() {
        try {
            const res = await nextApi.getClientList({ pageSize: 1000, pageNum: 1 });
            this.clientList = res.data.rows || [];
        } catch (e) {
            throw e;
        }
    }
    //选择物料类型
    varietyList: any = [];
    async getVarietyList(productType) {
        try {
            let params = {
                productType,
            };
            const res = await nextApi.getVarietyListByProductType(params);
            this.batchList = res.data.batchS || [];
            this.varietyList = res.data.varietyS || [];
        } catch (e) {
            throw e;
        }
    }
    //选择品种
    batchList: any = [];
    index: number = 0;
    async getDetailByVariety(materialCode, i) {
        this.index = i;
        this.categoryList[i].batch = "";
        let find = this.varietyList.find((item) => item.materialCode == materialCode);
        if (find) {
            let code = find.materialCode;
            this.categoryList[i].varietyName = find.varietyName;
            const res = await nextApi.getBatchByMaterialCode({ materialCode: code });
            this.batchList = res.data || [];
        }
    }
    //选择批号
    async getDetailInfo(batch, i) {
        this.categoryList[i].materialCode = "";
        this.categoryList[i].varietyName = "";
        this.categoryList[i].medicineClass = "";
        this.categoryList[i].medicineValue = "";
        this.index = i;
        let params = {
            productBatch: batch,
            productType: this.formData.productType,
        };
        const res = await nextApi.getInfoByTMB(params);
        if (res.code == 200 && res.data) {
            console.log("选择了批号");
            this.categoryList[this.index].varietyName = res.data.varietyName;
            this.categoryList[this.index].discretion = res.data.discretion;
            this.categoryList[this.index].productBigKind = res.data.productBigKind;
            this.categoryList[this.index].materialCode = res.data.materialCode;
            this.categoryList[this.index].medicineClass = res.data.medicineClass;
            this.categoryList[this.index].medicineValue = res.data.medicineValue;
            console.log(this.categoryList);
        } else {
            this.$message.error("该批次没有信息");
        }
    }
    //查询规格
    async getList() {
        this.pageList = [];
        try {
            this.loading = true;
            const res = await nextApi.getTableListOrDetail({
                pageNum: this.pagination.current,
                pageSize: this.pagination.pageSize,
            });
            this.pagination.total = res.data?.total || 0;
            this.pageList = res.data?.rows || [];
        } finally {
            this.loading = false;
        }
    }

    visible = false;
    async editDetail(item) {
        //调用查表格接口带上id查询详情
        const res = await nextApi.getTableListOrDetail({ id: item.id });
        this.formData = res.data;
        await this.getVarietyList(this.formData.productType);
        this.categoryList = this.formData.sellDetails;
        this.visible = true;
        console.log("详情：", this.formData);
    }
    checked = false;
    checkTableData = []
    async check(record:any) {
        this.checkModalOption.visible = true;
        const res = await nextApi.getTableListOrDetail({ id: record.id });
        let data = res.data
        this.checkTableData = data.sellDetails.map((item) => {
            return {
                ...item,
                clientName:data.clientName,
                erpOdd: data.erpOdd,
                productType:data.productType,
            }
        })
        console.log(this.checkTableData)
    }
    add() {
        this.formData = {
            clientName: "",
            sellTime: "",
            varietyNum: "",
            sellSum: "",
            sellDetails: [],
        };
        this.categoryList = [
            {
                varietyName: "",
                materialCode: "",
                batch: "",
                productBigKind: "",
                discretion: "",
                sellNum: "",
            },
        ];
        this.visible = true;
    }
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }
    mounted() {
        this.getList();
        this.getClientList();
    }
    modalOk() {
        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (valid) {
                //验证动态表单categoryList中每一个的batchS的batch不为空
                const isEmpty3 = this.categoryList.every((item) => item.batch);
                if (!isEmpty3) return this.$message.error("请选择批次");
                //验证动态表单categoryList中每一个的varietyName不为空
                const isEmpty2 = this.categoryList.every((item) => item.varietyName);
                if (!isEmpty2) return this.$message.error("请选择品种");
                //验证动态表单categoryList中每一个的batchS的sellNum不为空
                const isEmpty4 = this.categoryList.every((item) => item.sellNum);
                if (!isEmpty4) return this.$message.error("请输入销售数量");
                this.formLoading = true;
                try {
                    console.log("数据：", this.categoryList);
                    this.formData.varietyNum = this.categoryList.length;
                    this.formData.sellSum = this.categoryList.reduce((acc, item) => {
                        return acc + item.sellNum * 1;
                    }, 0);
                    this.formData.sellSum = this.formData.sellSum.toFixed(2);
                    this.formData.sellDetails = this.categoryList;
                    console.log("formData", this.formData);
                    const res = await nextApi.addSaleRecord(this.formData);
                    this.$message.success(res.msg);
                } catch (e) {
                    throw e;
                } finally {
                    this.getList();
                    this.formLoading = false;
                    this.visible = false;
                }
            }
        });
    }
    closeModal() {
        this.visible = false;
        (this.$refs.form as any).resetFields();
        this.checked = false;
    }
    async remove(records: any) {
        try {
            this.loading = true;
            const res = await nextApi.removeRecord(records.id);
            this.$message.success(res.msg);
        } finally {
            this.loading = false;
        }
        this.getList();
    }
    // 下载导入模板
    downloadTemplate() {
        try {
            this.loading = true;
            nextApi.downloadSellImportTemplate((res)=>{
                const blob = new Blob([res.data], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", //xlsx
                    // type: "application/vnd.ms-excel", //xls
                });
                downLoadFile(blob, "销售数据导入模板");
                this.$message.success('模板下载成功');
            })
        } catch (error) {
            this.$message.error('模板下载失败');
            console.error('下载模板失败:', error);
        } finally {
            this.loading = false;
        }
    }

    // 显示导入模态框
    showImportModal() {
        this.importModalVisible = true;
        this.selectedFile = null;
    }

    // 关闭导入模态框
    closeImportModal() {
        this.importModalVisible = false;
        this.selectedFile = null;
    }

    // 处理文件选择
    handleFileChange(info: any) {
        const file = info.file;
        if (file) {
            this.selectedFile = file;
        }
    }

    // 处理导入
    async handleImport() {
        if (!this.selectedFile) {
            this.$message.warning('请先选择要导入的文件');
            return;
        }

        try {
            this.importLoading = true;
            const formData = new FormData();
            formData.append('file', this.selectedFile);
            
            const res = await nextApi.importSellData(formData);
            this.$message.success(res.msg || '导入成功');
            this.closeImportModal();
            this.getList(); // 刷新列表
        } catch (error) {
            this.$message.error('导入失败');
            console.error('导入失败:', error);
        } finally {
            this.importLoading = false;
        }
    }
}
</script>
<style lang="scss">
.testing-index {
    padding: 20px;
}
</style>
